package com.okb.config.datasource;


import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.okb.config.mybatis.MapperLocationUtil;
import com.okb.config.mybatis.MybatisPlusConfig;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.okb.mapper", sqlSessionTemplateRef = "dataSqlSessionTemplate")
public class DataSourceDataConfig implements TransactionManagementConfigurer {

    @Resource
    private MybatisPlusConfig mybatisPlusConfig;

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return null;
    }

    @Bean(name = "dataTransactionManager")
    @Primary
    public PlatformTransactionManager dataTransactionManager() {
        return new DataSourceTransactionManager(dataSourceData());
    }

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.sea")
    public DataSource dataSourceData() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "dataSqlSessionTemplate")
    public SqlSessionTemplate dataSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(dataSqlSessionFactory());
    }

    @Bean(name = "dataSqlSessionFactory")
    @Primary
    public SqlSessionFactory dataSqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSourceData());
        bean.setPlugins(mybatisPlusConfig.mybatisPlusInterceptor());
        bean.setMapperLocations(MapperLocationUtil.resolveMapperLocations(new String[]{"classpath:mapper/**/*.xml"}));
        // 导入mybatis配置
        MybatisConfiguration configuration = new MybatisConfiguration();
        // 配置打印sql语句
        configuration.setLogImpl(StdOutImpl.class);
        bean.setConfiguration(configuration);
        bean.setTypeAliasesPackage("com.okb.vo");
//        bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:/mapper/**/*.xml"));
        return bean.getObject();
    }

}
